import { mapCompositionCoord } from './mapCompositionCoord.util'
import { mapFormatCoord } from './mapFormatCoord.util';

export function mergeFormatSvg(format, { colors, compositions, graphics, schemes, suites }) {
  let useTags = '';
  let symbolDefs = '';
  let graphicCoords = []
  let fillColors = {}

  // console.log({ colors, compositions, graphics, schemes });

  // generate symbol code
  format.elements.forEach(el => {
    const composition = compositions?.find(c => c.id === el.compositionId) || {};
    symbolDefs += genSymbols(composition, graphics)
  })

  // calc graphic coord for use
  format.elements.forEach(element => {
    const { compositionId } = element;
    const composition = compositions?.find(c => c.id === compositionId) || {};
    const compositionCoord = mapCompositionCoord(composition);
    const elemCoord = mapFormatCoord(format, element, compositionCoord);
    graphicCoords = [...graphicCoords, ...calceGraphicsCoord(compositionCoord, elemCoord)];
  })

  // get graphic color for use
  format.elements.forEach(element => {
    const { compositionId, schemeId } = element;
    const composition = compositions?.find(c => c.id === compositionId) || {};
    const scheme = schemes?.find(s => s.id === schemeId) || {};
    const { swatches } = scheme;
    for (const graphicId in swatches) {
      const colorId = swatches[graphicId];
      const color = colors.find(c => c.id === colorId);
      if (!color) { continue }
      fillColors[graphicId] = color.hex;
    }
  })

  // generate use code
  graphicCoords.forEach(graphicCoord => {
    const { x, y, width, height, graphicId } = graphicCoord;
    const symbolId = `graphic-${graphicId}`
    useTags += `<use xlink:href="#${symbolId}" x="${x}" y="${y}" width="${width}" height="${height}" fill="${fillColors[graphicId]}"/>`;
  })


  // Wrap the use tags in an svg tag
  const viewBox = `0 0 ${format.width} ${format.height}`
  let startTag = `<svg href:xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`

  // symbolDefs = TEMPLATE.symbolDefs
  // console.log(symbolDefs)
  // useTags = TEMPLATE.useTags
  // console.log(useTags)
  return `${startTag} ${symbolDefs} ${useTags} </svg>`;
}

export const TEMPLATE = {
  start: '<svg viewBox="0 0 2000 1000" xmlns="http://www.w3.org/2000/svg" fill="#fff">',
  symbolDefs: `
    <symbol id="graphic-1" viewBox="0 0 200 200">
      <circle cx="100" cy="100" r="100" />
    </symbol>
  `,
  useTags: '<use href="#graphic-1" x="0" y="0" width="500" height="500"/>',
  end: '</svg>',
}

function calceGraphicsCoord(compositionCoord, elemCoord) {
  const { x: elemX, y: elemY, width: elemWidth } = elemCoord;
  const { compWidth } = calcCompSize(compositionCoord);
  const scale = elemWidth / compWidth;
  const graphicCoords = []
  for (const direct in compositionCoord) {
    const { x: graphX, y: graphY, width: graphWidth, height: graphHeight, graphicId } = compositionCoord[direct];
    const graphicCoord = {
      x: (elemX + graphX * scale) || 0,
      y: (elemY + graphY * scale) || 0,
      width: (graphWidth * scale) || 0,
      height: (graphHeight * scale) || 0,
      graphicId,
    }
    graphicCoords.push(graphicCoord);
  }
  return graphicCoords
}

function genSymbols({ components }, graphics) {
  let symbolDefs = '';
  for (const direct in components) {
    const { graphicId } = components[direct]
    const graphic = graphics.find(g => g.id === graphicId)
    if (!graphic) continue

    const symbolId = `graphic-${graphicId}`;
    const viewBox = matchViewBox(graphic.svgCode);
    const svgContent = graphic.svgCode.trim()
      .replace(/<svg(S*?)[^>]*>/, '')
      .replace(/<\/svg>$/, '');    // Convert each SVG graphic to a symbol
    symbolDefs += `<symbol id="${symbolId}" viewBox="${viewBox}">${svgContent}</symbol>`;
  }
  return symbolDefs
}

function calcCompSize(coordinates) {
  let compWidth = 0; let compHeight = 0;
  for (const key in coordinates) {
    const { x, y, width, height } = coordinates[key];
    if (compWidth < x + width) { compWidth = x + width }
    if (compHeight < y + height) { compHeight = y + height }
  }
  return { compWidth, compHeight }
}

function matchViewBox(svgCode = '') {
  const viewBoxMatch = svgCode.match(/viewBox="([^"]+)"/);
  const match = svgCode.match(/viewBox="([^"]+)"/);
  return match ? match[1] : null;
}


// Example usage
export const mockFormat =
{
  "id": 3,
  "name": "a4",
  "brandId": 1,
  "suiteId": 2,
  "width": 285,
  "height": 210,
  "backgroundColorId": 2,
  "elements": [{
    "compositionId": 3,
    "schemeId": 2,
    "height": 30,
    "right": 10,
    "bottom": 10
  }],
  "suite": {
    "id": 2,
    "brandId": 1,
    "name": "print",
    "medium": "print",
    "based": "short",
    "usePercentSize": false,
    "unit": "mm",
    "colorMode": "cmyk"
  }
}
/*
{
  "id": 1,
  "name": "iphone",
  "brandId": 1,
  "suiteId": 1,
  "width": 2000,
  "height": 1000,
  "backgroundColorId": 4,
  "elements": [
    {
      "compositionId": 1,
      "schemeId": 1,
      "height": 300,
      "left": -250,
      "top": -100,
    }, {
      "compositionId": 1,
      "schemeId": 1,
      "height": 500,
      "center": 0,
      "top": 0,
    }
  ],
  "suite": {
    "id": 1,
    "brandId": 1,
    "name": "mobile",
    "medium": "web",
    "based": "short",
    "usePercentSize": false,
    "unit": "px",
    "colorMode": "rgb"
  }
}
*/



// const mergedSVGCode = mergeSVGGraphics(graphics);
// console.log(mergedSVGCode);
